/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bionic.ce.managedbeans;

import com.bionic.ce.entities.Query;
import com.bionic.ce.entities.Systemacc;
import com.bionic.ce.entitybeans.query.QueryFacadeLocal;
import com.bionic.ce.entitybeans.systemacc.SystemaccFacadeLocal;
import com.bionic.ce.logic.QueriesService;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author Jarik
 */
@ManagedBean(name = "queriesManagedBean")
@SessionScoped
public class QueriesManagedBean implements Serializable {

    public QueriesManagedBean() {
        query = new Query();
    }
    @EJB
    private QueryFacadeLocal queryEJB;
    @EJB
    private SystemaccFacadeLocal systemAccEJB;
    public Query query = new Query();
    public Query serchQuery = new Query();
    List<Query> queryList = new ArrayList<Query>();
    @ManagedProperty("#{userManagedBean}")
    private UserManagedBean userMB;
    @ManagedProperty("#{currencyManagedBean}")
    private CurrencyManagedBean currencyMB;
    @ManagedProperty("#{bankAccManagedBean}")
    private BankAccManagedBean bankAccMB;
    @ManagedProperty("#{systemAccManagedBean}")
    private SystemAccManagedBean systemAccMB;

    public Query getQuery() {
        return query;
    }

    public void setQuery(Query query) {
        this.query = query;
    }

    public Query getSerchQuery() {
        return serchQuery;
    }

    public void setSerchQuery(Query serchQuery) {
        this.serchQuery = serchQuery;
    }

    public List<Query> getQueryList() {
        return queryList;
    }

    public void setQueryList(List<Query> queryList) {
        this.queryList = queryList;
    }

    public BankAccManagedBean getBankAccMB() {
        return bankAccMB;
    }

    public void setBankAccMB(BankAccManagedBean bankAccMB) {
        this.bankAccMB = bankAccMB;
    }

    public CurrencyManagedBean getCurrencyMB() {
        return currencyMB;
    }

    public void setCurrencyMB(CurrencyManagedBean currencyMB) {
        this.currencyMB = currencyMB;
    }

    public SystemAccManagedBean getSystemAccMB() {
        return systemAccMB;
    }

    public void setSystemAccMB(SystemAccManagedBean systemAccMB) {
        this.systemAccMB = systemAccMB;
    }

    public SystemaccFacadeLocal getSystemAccEJB() {
        return systemAccEJB;
    }

    public void setSystemAccEJB(SystemaccFacadeLocal systemAccEJB) {
        this.systemAccEJB = systemAccEJB;
    }

    public QueryFacadeLocal getQueryEJB() {
        return queryEJB;
    }

    public void setQueryEJB(QueryFacadeLocal queryEJB) {
        this.queryEJB = queryEJB;
    }

    public UserManagedBean getUserMB() {
        return userMB;
    }

    public void setUserMB(UserManagedBean userMB) {
        this.userMB = userMB;
    }

    //проверка на возможность создания или обновление существующей заявки на обмен
    public boolean validateQuery() {
        query.setOpenByUser(userMB.user);
        query.setStatus("Active");
        query.setOpenDate(new Date());
        boolean b = false;
        if (query.getAmount() <= 0) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Query adding error: ", "Amount must be positive"));
        } else if (query.getCurrencyFrom().equals(query.getCurrencyTo())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Query adding error: ", "Currency from and Currency to can`t be the same"));
        } else if (query.getRateFrom() > query.getRateTo()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Query adding error: ", "Rate from couldn`t be more than Rate to"));
        } else if (query.getFinishDate().before(query.getOpenDate())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Query adding error: ", "Wrong value of finish date"));
        } else if (systemAccEJB.findByUserIdAndCurrency(userMB.getUser().getId(), query.getCurrencyFrom().getShortName()).isEmpty()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Query adding error: ",
                    "You can`t exchange money from " + query.getCurrencyFrom().getShortName()
                    + " to " + query.getCurrencyTo().getShortName() + " because you don`t have system account in "
                    + query.getCurrencyFrom().getShortName()));
        } else {
            Systemacc systemAcc = (Systemacc) (systemAccEJB.findByUserIdAndCurrency(userMB.getUser().getId(), query.getCurrencyFrom().getShortName()).toArray())[0];
            if (query.getAmount() > systemAcc.getAmount()) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Query adding error: ", "You don`t have enough money on yours System account in " + query.getCurrencyFrom().getShortName()));
            } else {
                Double activeQueriesSum = QueriesService.balancecheck(userMB.getUser().getId(), query.getCurrencyFrom().getShortName());
                System.out.println("XXXXXX" + activeQueriesSum);
                System.out.println("getAmount" + query.getAmount());
                System.out.println("systemAcc.getAmount()" + systemAcc.getAmount());
                if (query.getAmount() > (systemAcc.getAmount() - activeQueriesSum)) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Query adding error: ", "You don`t have enough money on yours system account in "
                            + query.getCurrencyFrom().getShortName() + " to place one more query. The balance in your account is "
                            + systemAcc.getAmount() + " " + query.getCurrencyFrom().getShortName() + " and total of your queries is " + activeQueriesSum + " " + query.getCurrencyFrom().getShortName() + "."));
                } else {
                    b = true;
                }
            }
        }
        return b;
    }
    //проверка на возможность обмена заявки выбраной из списка активных заявок

    public boolean validateExchangeOfSelectedQuery() {

        boolean b = false;
        if (systemAccEJB.findByUserIdAndCurrency(userMB.getUser().getId(), query.getCurrencyFrom().getShortName()).isEmpty()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Query adding error: ",
                    "You can`t exchange money from " + query.getCurrencyFrom().getShortName()
                    + " to " + query.getCurrencyTo().getShortName() + " because you don`t have system account in "
                    + query.getCurrencyFrom().getShortName()));
        } else if (systemAccEJB.findByUserIdAndCurrency(userMB.getUser().getId(), query.getCurrencyTo().getShortName()).isEmpty()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Query adding error: ",
                    "You can`t exchange money from " + query.getCurrencyFrom().getShortName()
                    + " to " + query.getCurrencyTo().getShortName() + " because you don`t have system account in "
                    + query.getCurrencyTo().getShortName()));
        } else {
            Systemacc systemAcc = (Systemacc) (systemAccEJB.findByUserIdAndCurrency(userMB.getUser().getId(), query.getCurrencyTo().getShortName()).toArray())[0];
            Double activeQueriesSum = QueriesService.balancecheck(userMB.getUser().getId(), query.getCurrencyTo().getShortName());
            if (query.getAmount() > systemAcc.getAmount() - activeQueriesSum) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Query adding error: ", "You don`t have enough money on yours System account in " + query.getCurrencyTo().getShortName() + " to execute this query. The balance in your account is "
                        + systemAcc.getAmount() + " " + query.getCurrencyTo().getShortName() + " and total of your queries is " + activeQueriesSum + " " + query.getCurrencyTo().getShortName() + "."));
            } else {
                systemAccEJB.executedQueryMoneyTransfer(query.getOpenByUser(), query.getCurrencyFrom(), query.getCurrencyTo(), userMB.getUser(), query.getAmount(), query.getAmount() * query.getRateFrom());
                query.setStatus("Executed By User");
                query.setClosedRate(query.getRateFrom());
                query.setClosedDate(new Date());
                query.setExecutedByUser(userMB.getUser());
                queryEJB.edit(query);
                b = true;
            }
        }
        return b;
    }
    // создание новой заявки

    public String doAddQuery() {
        String page = null;
        if (validateQuery()) {
            queryEJB.create(query);
            Double d = QueriesService.autoExchange(query);
            if (d != null) {
                page = systemAccMB.doShowList();
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Query was automatically exchanged. ",
                        "From yours system account were withdrawed " + String.format("%.2f", query.getAmount()) + " " + query.getCurrencyFrom().getShortName() + " "
                        + " and were deposited " + String.format("%.2f", d) + " " + query.getCurrencyTo().getShortName() + "."));
            } else {
                page = doShowMyActiveQueries();
            }
        }
        query = new Query();
        return page;
    }
    //обновление существующей заявки

    public String doUpdateQuery() {
        String page = null;
        if (validateQuery()) {
            queryEJB.edit(query);
            Double d = QueriesService.autoExchange(query);
            if (d != null) {
                page = systemAccMB.doShowList();
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Query was automatically exchanged. ",
                        "From yours system account were withdrawed " + String.format("%.2f", query.getAmount()) + " " + query.getCurrencyFrom().getShortName() + " "
                        + " and were deposited " + String.format("%.2f", d) + " " + query.getCurrencyTo().getShortName() + "."));
            } else {
                page = doShowMyActiveQueries();
            }
        }
        query = new Query();
        return page;
    }

    public String doDeleteQuery() {
        queryEJB.remove(query);
        query = new Query();
        return doShowMyActiveQueries();
    }

    public String goToAddQuery() {
        query = new Query();
        return "/pages/query/addquery.xhtml?faces-redirect=true";
    }

    public String goToUpdateQuery() {
        if (query.getId() != null) {
            return "/pages/query/updatequery.xhtml?faces-redirect=true";
        } else {
            return null;
        }
    }

    //возврат страницы активных заявок
    public String doShowActiveQueries() {
        queryList = QueriesService.check(null);
        query = new Query();
        return "/pages/query/activequeries.xhtml?faces-redirect=true";
    }
    //возврат страницы с таблицей активных заявок

    public String doShowActiveQueriesList() {
        queryList = QueriesService.check(null);
        query = new Query();
        return "/pages/query/querylist.xhtml";
    }
    //возврат страницы с таблицей активных заявок для даного пользователя

    public String doShowMyActiveQueries() {
        queryList = QueriesService.check(userMB.getUser().getId());
        query = new Query();
        return "/pages/query/myactivequeries.xhtml?faces-redirect=true";
    }
    //возврат страницы с таблицей истории заявок для даного пользователя

    public String doShowMyNotActiveQueries() {
        QueriesService.expirationCheck();
        queryList = queryEJB.findNotActiveQueries(userMB.getUser().getId());
        query = new Query();
        return "/pages/query/mynotactivequeries.xhtml?faces-redirect=true";
    }
    //обмен заявки выбраной из списка активных заявок

    public String doExchangeQuery() {
        String page = null;
        if (validateExchangeOfSelectedQuery()) {
            page = systemAccMB.doShowList();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Query was automatically exchanged. ",
                    "From yours system account were withdrawed " + String.format("%.2f", query.getAmount() * query.getRateFrom()) + " " + query.getCurrencyTo().getShortName() + " "
                    + " and were deposited " + String.format("%.2f", query.getAmount()) + " " + query.getCurrencyFrom().getShortName() + "."));
        }
        query = new Query();
        return page;
    }
    //переход на страницу поиска заявок

    public String doSearchSelected() {
        String page = null;
        serchQuery = new Query();
        return "/pages/query/searchqueries.xhtml?faces-redirect=true";
    }
    //возврат страницы с результатами поиска заявок с задынными ранее критериями поиска

    public String doShowSearchResults() {
        String page = null;
        serchQuery.setStatus("Active");
        queryList = queryEJB.findByDynamicSelect(serchQuery);
        return "/pages/query/activequeries.xhtml?faces-redirect=true";
    }
}
